<?php
namespace app\common\library\delivery;

/**
 * 达达配送
*/
class Dada
{
	private $callback = 'https://food.cityphp.cn/dada.php';	//回调URL（查看回调说明）
    private $app_key = 'dada48bde1c6ff17ff0';	//开发者app_key
    private $app_secret = 'ab39ebd50ad2ef1bb2cb8d23b2d2dcd0';	//发者app_secret
	private $host = 'http://newopen.qa.imdada.cn';	//api接口地址
	private $source_id = '73753';	//商户ID(测试号：)
	private $shop_no = '11047059';	//门店编号ID
	private $businessParams = '';//请求数据（body内容）
	private $is_prepay = 0;	//是否需要垫付 1:是 0:否 (垫付订单金额，非运费)
	private $format = "json";	//数据格式
    private $v = "1.0";	//api版本
	/*
	门店编码：52255-523901
	区域负责人：客服-4009919512
	商户编号(source_id):52255
	账户ID:28295053
	*/
    /**
     * 构造函数
     
    public function __construct(){
            //$this->source_id = $source_id;
            //$this->host = "https://newopen.imdada.cn";
			//http://newopen.qa.imdada.cn 测试地址
    }
	*/
	/**
     * 添加一个订单
     
	public function addOrder($order,$set)
	{	
		$coordinate = explode(',',$order['order']['address']['location']);
		$order = [
			'shop_no' => $set['shop_no']//门店编号
			'origin_id' => $order['order_no'],//第三方订单ID
			'city_code' => $set['city_code'],//所在城市的code
			'cargo_price' => $order['pay_price'],//订单金额
			'is_prepay' => $this->is_prepay,//是否需要垫付 1:是 0:否 (垫付订单金额，非运费)
			'receiver_name' => $order['order']['address']['name'],//收货人姓名
			'receiver_address' => $order['order']['address']['detail'],//收货人地址
			'receiver_phone' => $order['order']['address']['phone'],//收货人手机号
			'receiver_lat' => $coordinate[0],//地址维度
			'receiver_lng' => $coordinate[1],//地址经度
			'callback' => $this->callback,//回调URL
		];
		$this->businessParams = json_encode($order);
		$data = $this->bulidRequestParams();
		$res = $this->getHttpRequestWithPost($data,'/api/order/addOrder');
		if($res['status'] == 'fail'){
			//如果推送失败，连续推送5次
			for($n=0;$n<5;$n++){
				$res = $this->getHttpRequestWithPost($data,'/api/order/addOrder');
				if($res['status'] == 'success'){
					break;
				}
			}
		}
        return $res;
	}
	*/
	
    
	/**
     * 获取城市编码
     
	public function getCity()
	{
		$data = $this->bulidRequestParams();
		$data['app_secret'] = $this->app_secret;
		$res = $this->getHttpRequestWithPost($data,'/api/cityCode/list');
		write_log($res,__DIR__);
		
	}
	*/
    
	/**
     * 添加门店
     */
	public function add_shop($data)
	{
		$this->businessParams = json_encode($data,JSON_UNESCAPED_UNICODE);
		$data = $this->bulidRequestParams();
		$res = $this->getHttpRequestWithPost($data,'/api/shop/add');
		if($res['status']=='success' AND $res['result']['success']>0){
			/*return [
				'shop_no' => $res['result']['successList'][0]['originShopId'],
				'city_code' => $this->getCiytCode($res['result']['successList'][0]['cityName']),
			];*/
			return true;
		}
		return false;
	}
	
	/**
     * 获取城市编码
     */
	private function getCiytCode($city)
	{
		$data = $this->bulidRequestParams();
		$data['app_secret'] = $this->app_secret;
		$res = $this->getHttpRequestWithPost($data,'/api/cityCode/list');
		$code = '';
		for($n=0;$n<sizeof($res['result']);$n++){
			if($res['result'][$n]['cityName'] == $city){
				$code = $res['result'][$n]['cityCode'];
				break;
			}
		}
		return $code;
	}

    /**
     * 发送请求,POST
     * @param $url 指定URL完整路径地址
     * @param $data 请求的数据
     */
    private function getHttpRequestWithPost($data,$url){
		$data = json_encode($data,JSON_UNESCAPED_UNICODE);
        $url = $this->host . $url;
        // json
        $headers = array(
            'Content-Type: application/json',
        );
        $curl = curl_init($url);
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HEADER, false);
        curl_setopt($curl, CURLOPT_POST, true);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        curl_setopt($curl, CURLOPT_TIMEOUT, 3);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        $resp = curl_exec($curl);
        var_dump( curl_error($curl) );//如果在执行curl的过程中出现异常，可以打开此开关查看异常内容。
        $info = curl_getinfo($curl);
        curl_close($curl);
        if (isset($info['http_code']) && $info['http_code'] == 200) {
            return json_decode($resp, true);
        }
        return '';
    }
	
	/**
     * 构造请求数据
     * data:业务参数，json字符串
     */
    private function bulidRequestParams(){
        $requestParams = array();
        $requestParams['app_key'] = $this->app_key;
        $requestParams['body'] = $this->businessParams;
        $requestParams['format'] = $this->format;
        $requestParams['v'] = $this->v;
        $requestParams['source_id'] = $this->source_id;
        $requestParams['timestamp'] = time();
        $requestParams['signature'] = $this->_sign($requestParams);
        return $requestParams;
    }

    /**
     * 签名生成signature
     */
    private function _sign($data){
		
        //1.升序排序
        ksort($data);

        //2.字符串拼接
        $args = "";
        foreach ($data as $key => $value) {
            $args.=$key.$value;
        }
        $args = $this->app_secret . $args . $this->app_secret;
        //3.MD5签名,转为大写
        $sign = strtoupper(md5($args));
        return $sign;
    }
	
	
}
